#include <pthread.h>
#include <sys/select.h>
#include <sys/socket.h>
#include <sys/un.h>

#define NIT_SHORT_NAMES
#include <nit/socket.h>

typedef struct {
	const char *str;
} Str_carrier;

#define STR_CARRIER(PTR) ((Str_carrier *) (PTR))

Nit_joint *
t3_io_single(const char *name)
{
	Nit_joint *jnt;
	Nit_joiner *jnr = joiner_new(name);

	if (!jnr)
		return NULL;

	jnt = joiner_accept(jnr);
	joiner_free(jnr);
	return jnt;
}

static void *
other_wait(void *tmp)
{
	pthread_exit(t3_io_single(STR_CARRIER(tmp)->str));
}

int
t3_io_both(const char *name1, const char *name2,
	   Nit_joint **jnt1_ref, Nit_joint **jnt2_ref)
{
	Nit_joint *jnt1;
	void *jnt2;
	pthread_t thread;
	Nit_joiner *jnr = joiner_new(name1);
	Str_carrier tmp = { .str = name2 };

	if (!jnr)
		return 0;

	if (pthread_create(&thread, NULL, other_wait, &tmp)) {
		joiner_free(jnr);
		return 0;
	}

	jnt1 = joiner_accept(jnr);
	joiner_free(jnr);

	if (pthread_join(thread, &jnt2)) {
		if (jnt1)
			joint_free(jnt1);

		return 0;
	}

	if (!jnt1) {
		if (jnt2)
			joint_free(jnt2);

		return 0;
	}

	if (!jnt2) {
		joint_free(jnt1);
		return 0;
	}

	*jnt1_ref = jnt1;
	*jnt2_ref = jnt2;
	return 1;
}
